package com.quyunshuo.module.home.activity.history

import androidx.lifecycle.viewModelScope
import com.quyunshuo.edwinpro.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.fragment.me.Resource
import com.quyunshuo.module.home.room.entity.ConcentrationEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 首页的VM层
 *
 * @property mRepository HomeRepository 仓库层 通过Hilt注入
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:41 PM
 */
@HiltViewModel
class HistoryViewModel @Inject constructor(private val mRepository: HistoryRepository) : BaseViewModel() {
    private val _dataAll = MutableStateFlow<Resource<List<ConcentrationEntity>>>(Resource.Loading)
    val dataAll: StateFlow<Resource<List<ConcentrationEntity>>> = _dataAll.asStateFlow()

    val dataAllFlow = mRepository.getAllConcentration()
        .stateIn(viewModelScope, SharingStarted.Lazily, emptyList())

    init {
        getAll()
    }

    fun getAll(){
        viewModelScope.launch {
            val all = mRepository.getAll()
            //拿到数据以后呢？
            _dataAll.emit(Resource.Success(all))
        }
    }
    fun deleteById(id:Long){
        viewModelScope.launch {
            mRepository.deleteById(id)
//            getAll() 不需要重新查询，dataAllFlow自动刷新的
        }


    }
}
